package com.csit.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.csit.bean.Pager;
import com.csit.dao.ProductDao;
import com.csit.entity.Product;
import com.csit.util.StringUtil;

@Repository
public class ProductDaoImpl extends BaseDaoImpl<Product, Integer> implements ProductDao {

	public Pager queryProduct(Pager pager, Product product) {
		Criteria criteria = getSession().createCriteria(Product.class);
		criteria.add(Restrictions.eq("shop", product.getShop()));
		if(product.getProductItem()!=null&&product.getProductItem().getDataDictionaryID()!=null){
			criteria.add(Restrictions.eq("productItem", product.getProductItem()));
		}
		if(StringUtil.isNotNull(product.getProductCode())){
			criteria.add(Restrictions.like("productCode", product.getProductCode(), MatchMode.ANYWHERE));
		}
		if(StringUtil.isNotNull(product.getProductName())){
			criteria.add(Restrictions.like("productName", product.getProductName(), MatchMode.ANYWHERE));
		}
		
		Long totalCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();

		criteria.setProjection(null);
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		criteria.setFirstResult(pager.getBeginCount());
		criteria.setMaxResults(pager.getPageSize());
		criteria.addOrder(Order.asc("productCode"));
		pager.setTotalCount(totalCount);
		pager.setList(criteria.list());
		return pager;
	}

}
